package com.isoftstone;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;

import com.isoftstone.activity.DialogBase;
import com.isoftstone.activity.DialogBase.Builder;
import com.isoftstone.activity.ImagePagerActivity;
import com.isoftstone.util.RUtil;
import com.qihoo.updatesdk.lib.UpdateHelper;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

public class TravelPlugin extends CordovaPlugin implements IWXAPIEventHandler {
  private IWXAPI api;
  public static final String APP_ID = "wx9524e083be1db435";

  public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    RUtil.instance = new RUtil(cordova.getActivity());
    api = WXAPIFactory.createWXAPI(this.cordova.getActivity(), APP_ID, false);
    api.registerApp(APP_ID);
    api.handleIntent(this.cordova.getActivity().getIntent(), this);
  }

  @Override
  public boolean execute(String action, JSONArray args,
                         CallbackContext callbackContext) throws JSONException {
    ArrayList<String> imgUrls = new ArrayList<String>();
    int imgIndex = 0;
    if ("showImages".equals(action)) {
      if (args != null && args.length() > 0) {
        for (int i = 0; i < args.length(); i++) {
          String url = args.getString(i);
          if (url != null && !url.equals("")) {
            if (url.length() < 3) {
              imgIndex = Integer.parseInt(url);
            } else {
              url = this.encoderUrl(url);
              imgUrls.add(url);
            }
          }
        }
      }

      Intent it = new Intent(this.cordova.getActivity(),
        ImagePagerActivity.class);
      it.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, imgUrls);
      it.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, imgIndex);
      this.cordova.getActivity().startActivity(it);
    } else if ("exitApp".equals(action)) {
      exitApp();
    } else if ("updateVersion".equals(action)) {
      updateVersion();
    } else if ("dail".equals(action)) {
      if (args != null && args.length() > 0) {
        String phone = args.optString(0);
        dail(phone);
      }
    } else if ("openExternalUrl".equals(action)) {
      if (args != null && args.length() > 0) {
        String url = args.optString(0);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        //打开默认浏览器
        // this.cordova.getActivity().startActivity(intent);
        //选择浏览器
        this.cordova.getActivity().startActivity(Intent.createChooser(intent, "请选择浏览器"));
      }
    } else if ("startNavigator".equals(action)) {
      if (args != null && args.length() == 3) {
        String type = args.getString(0);
        String user_location = args.getString(1);
        String site_location = args.getString(2);
        startNavigator(type, user_location, site_location);
      }
    } else if ("share".equals(action)) {
      if (args != null && args.length() == 3) {
        String title = args.getString(0);
        String description = args.getString(1);
        String url = args.getString(2);
        showpopWindow(title, description, url);
      }
    }
    return true;
  }

  private void showpopWindow(final String title, final String description, final String url) {
    // 用于PopupWindow的View
    View contentView = LayoutInflater.from(this.cordova.getActivity()).inflate(RUtil.instance.getLayout("plugin_popwindow_share"), null, false);
    LinearLayout ll_wx = (LinearLayout) contentView.findViewById(RUtil.instance.getId("ll_wx"));
    LinearLayout ll_wx_friend = (LinearLayout) contentView.findViewById(RUtil.instance.getId("ll_wx_friend"));
    LinearLayout ll_popwindow_background = (LinearLayout) contentView.findViewById(RUtil.instance.getId("ll_popwindow_background"));
    ll_wx.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        shareApp(false, title, description, url);
      }
    });
    ll_wx_friend.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        shareApp(true, title, description, url);
      }
    });


    // 创建PopupWindow对象，其中：
    // 第一个参数是用于PopupWindow中的View，第二个参数是PopupWindow的宽度，
    // 第三个参数是PopupWindow的高度，第四个参数指定PopupWindow能否获得焦点
    final PopupWindow window = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
      ViewGroup.LayoutParams.MATCH_PARENT, true);
    // 设置PopupWindow的背景
    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    // 设置PopupWindow是否能响应外部点击事件
    window.setOutsideTouchable(true);
//    window.setBackgroundDrawable(new ColorDrawable(0));
    // 设置PopupWindow是否能响应点击事件
    window.setTouchable(true);
    ll_popwindow_background.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        window.dismiss();
      }
    });
    // 显示PopupWindow，其中：
    // 第一个参数是PopupWindow的锚点，第二和第三个参数分别是PopupWindow相对锚点的x、y偏移
//    window.showAsDropDown(anchor, 0, 0);
    // 或者也可以调用此方法显示PopupWindow，其中：
    // 第一个参数是PopupWindow的父View，第二个参数是PopupWindow相对父View的位置，
    // 第三和第四个参数分别是PopupWindow相对父View的x、y偏移
    window.showAtLocation(this.cordova.getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);

  }

  public static void backgroundAlpha(Activity context, float bgAlpha) {
    WindowManager.LayoutParams lp = context.getWindow().getAttributes();
    lp.alpha = bgAlpha;
    context.getWindow()
      .addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    context.getWindow().setAttributes(lp);
  }

  public static void removebackgroundAlpha(Activity context) {
    // TODO Auto-generated method stub
    context.getWindow().clearFlags(
      WindowManager.LayoutParams.FLAG_DIM_BEHIND);
  }

  private void shareApp(boolean isTimeLine, String title, String description, String url) {
    // WXSceneTimeline---分享到朋友圈
    // WXSceneSession---分享到微信好友
    WXWebpageObject webpage = new WXWebpageObject();
    // webpage.webpageUrl = Constant.STR_DOMAIN_HXY +
    // "Common/app/Index.htm";
    webpage.webpageUrl = url;

    WXMediaMessage msg = new WXMediaMessage(webpage);
    msg.title = title;
    msg.description = description;
    Bitmap thumb = BitmapFactory.decodeResource(this.cordova.getActivity().getResources(),
      RUtil.instance.getDrawable("icon"));
    msg.thumbData = bmpToByteArray(thumb, true);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");
    req.message = msg;
    req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
      : SendMessageToWX.Req.WXSceneSession;
    api.sendReq(req);
  }

  private String buildTransaction(final String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis())
      : type + System.currentTimeMillis();
  }

  private byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
    if (needRecycle) {
      bmp.recycle();
    }

    byte[] result = output.toByteArray();
    try {
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }

  private void dail(String phone) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    Uri data = Uri.parse("tel:" + phone);
    intent.setData(data);
    this.cordova.getActivity().startActivity(intent);
  }

  /**
   * 检查手机上是否安装了指定的软件
   *
   * @param context
   * @param packageName：应用包名
   * @return
   */
  private boolean isAvilible(Context context, String packageName) {
    //获取packagemanager
    final PackageManager packageManager = context.getPackageManager();
    //获取所有已安装程序的包信息
    List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
    //用于存储所有已安装程序的包名
    List<String> packageNames = new ArrayList<String>();
    //从pinfo中将包名字逐一取出，压入pName list中
    if (packageInfos != null) {
      for (int i = 0; i < packageInfos.size(); i++) {
        String packName = packageInfos.get(i).packageName;
        packageNames.add(packName);
      }
    }
    //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
    return packageNames.contains(packageName);
  }

  private void startNavigator(String type, String user_location, String site_location) {
    if (type.equals("drive")) {
      if (isAvilible(this.cordova.getActivity(), "com.baidu.BaiduMap")) {
        //百度地图官方URI api
        Intent i1 = new Intent();
        // 驾车导航
        // String location = site_location.get("Latitude").toString()+","+site_location.get("Longitude").toString();
        i1.setData(Uri.parse("baidumap://map/navi?location=" + site_location));
        this.cordova.getActivity().startActivity(i1);
      } else {
        Toast.makeText(this.cordova.getActivity(), "请安装百度地图！", Toast.LENGTH_SHORT).show();
      }
    } else if (type.equals("walk")) {
      if (isAvilible(this.cordova.getActivity(), "com.baidu.BaiduMap")) {
        //百度地图官方URI api
        Intent i1 = new Intent();
        // 步行导航

        // //起点坐标点
        // String origin = site_location.get("Latitude").toString()+","+site_location.get("Longitude").toString();
        // //终点坐标点
        // String destination = site_location.get("Latitude").toString()+","+site_location.get("Longitude").toString();
        i1.setData(Uri.parse("baidumap://map/walknavi?origin=" + user_location + "&destination=" + site_location));
        this.cordova.getActivity().startActivity(i1);
      } else {
        Toast.makeText(this.cordova.getActivity(), "请安装百度地图！", Toast.LENGTH_SHORT).show();
      }
    }
  }

  private void updateVersion() {
    UpdateHelper.getInstance().autoUpdate(this.cordova.getActivity().getPackageName());
  }

  public String encoderUrl(String url) {
    int length = url.length();
    String s = "";
    for (int i = 0; i < length; i++) {
      char c = url.charAt(i);
      if (isChinese(c)) {
        s += URLEncoder.encode(String.valueOf(c));
      } else if (Character.isSpace(c)) {
        s += "%20";
      } else {
        s += c;
      }
    }
    return s;
  }

  public boolean isChinese(char c) {
    if ((c >= 0x4e00) && (c <= 0x9fbb)) {
      return true;
    }
    return false;
  }

  public void exitApp() {
    showAlertDialog("提示", "确定退出应用？", "确定", quitButtonClickListener, "取消",
      quitButtonClickListener);
  }

  protected void showAlertDialog(String title, String message,
                                 String positiveText,
                                 DialogInterface.OnClickListener onPositiveClickListener,
                                 String negativeText,
                                 DialogInterface.OnClickListener onNegativeClickListener) {
    showAlertDialog(this.cordova.getActivity(), title, message,
      positiveText, onPositiveClickListener, negativeText,
      onNegativeClickListener);
  }

  public static void showAlertDialog(Context context, String title,
                                     String message, String positiveText,
                                     DialogInterface.OnClickListener onPositiveClickListener,
                                     String negativeText,
                                     DialogInterface.OnClickListener onNegativeClickListener) {
    DialogBase.Builder builder = new Builder(context);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton(positiveText, onPositiveClickListener);
    builder.setNegativeButton(negativeText, onNegativeClickListener);
    Dialog dialog = builder.create();
    setCustomDialogSize(dialog, context);
    dialog.show();
  }

  public static void setCustomDialogSize(Dialog dialog, Context context) {
    Window dialogWindow = dialog.getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    lp.width = (int) (getScreenWidth(context) * 0.8);
    dialogWindow.setAttributes(lp);
  }

  public static int getScreenWidth(Context context) {
    WindowManager wm = (WindowManager) context
      .getSystemService(Context.WINDOW_SERVICE);
    return wm.getDefaultDisplay().getWidth();
  }

  private DialogInterface.OnClickListener quitButtonClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      switch (which) {
        case DialogInterface.BUTTON_POSITIVE: {
          dialog.dismiss();
          System.exit(0);
          break;
        }
        case DialogInterface.BUTTON_NEGATIVE: {
          dialog.dismiss();
          break;
        }
        default:
          break;
      }
    }
  };

  @Override
  public void onReq(BaseReq req) {
    Toast.makeText(this.cordova.getActivity(), req.getType(), Toast.LENGTH_LONG).show();
  }

  @Override
  public void onResp(BaseResp resp) {
    Toast.makeText(this.cordova.getActivity(), resp.errCode, Toast.LENGTH_LONG).show();
  }
}
